package meijuli.com.join51.business.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.liaoinstan.springview.widget.SpringView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.activity.AddCommodityActivity;
import meijuli.com.join51.business.activity.CommodityDetailActivity;
import meijuli.com.join51.business.adapter.CustomAdapter;
import meijuli.com.join51.business.adapter.CustomHolder;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import meijuli.com.join51.business.model.Commodity;
import meijuli.com.join51.business.model.CommodityData;
import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.ui.LoadFooterView;
import meijuli.com.join51.business.ui.RefreshHeaderView;
import meijuli.com.join51.business.ui.widget.CustomItemDecoration;
import com.jhx.common.utils.DisplayUtil;
import com.jhx.common.utils.ToastUtil;
import retrofit2.Call;

/**
 * 商品列表页
 *
 * @author jack 2017-04-25 10:36
 */
public class CommodityListFragment extends BaseFragment {
    SpringView mPullView;
    RecyclerView mRecyclerView;
    ViewStub emptyViewStub;
    LinearLayout mContentViewLayout;

    public static final String KEY_CATEGORY_ID = "categoryId";
    public static final String KEY_INDEX = "index";
    //上架
    private static final int STATUS_ON = 1;
    //下架
    public static final int STATUS_OFF = 0;
    private List<Commodity> mCommodityList;
    private CustomAdapter<Commodity> mAdapter;
    private int pageIndex = 1;
    private boolean isLoading = false;
    private boolean isRefresh = true;
    private Call<HttpResponse<CommodityData>> mCall;
    private  Call<HttpResponse<String>> call;
    //是否还能加载
    private boolean isMore = true;
    private String id = "";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_commodity_list, container, false);
        mPullView = view.findViewById(R.id.springview);
        mRecyclerView = view.findViewById(R.id.recyclerview);
        emptyViewStub = view.findViewById(R.id.viewstub_empty);
        mContentViewLayout = view.findViewById(R.id.ll_content_view);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return view;
    }

    public static CommodityListFragment newInstance(String id, int index) {
        CommodityListFragment fragment = new CommodityListFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_CATEGORY_ID, id);
        bundle.putInt(KEY_INDEX, index);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mPullView.setHeader(new RefreshHeaderView(getActivity()));
        mPullView.setFooter(new LoadFooterView(getActivity()));
        mPullView.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                if (isLoading) {
                    mPullView.onFinishFreshAndLoad();
                    return;
                }
                pageIndex = 1;
                isLoading = true;
                isRefresh = true;
                loadData(id);
            }

            @Override
            public void onLoadmore() {
                if (isLoading) {
                    mPullView.onFinishFreshAndLoad();
                    return;
                }
                if (!isMore) {
                    mPullView.onFinishFreshAndLoad();
                    ToastUtil.getInstance().showToast(getActivity(), "没有更多数据啦...");
                    return;
                }
                isLoading = true;
                isRefresh = false;
                loadData(id);
            }
        });

        mCommodityList = new ArrayList();
        mAdapter = new CustomAdapter<Commodity>(mCommodityList,
                getActivity(),
                R.layout.item_commodity,
                null) {
            @Override
            public void onBindData(CustomHolder holder, final int position, final Commodity commodity) {
                ImageView imageView = holder.findView(R.id.iv_commodity);
                TextView offText = holder.findView(R.id.text_del);
                TextView editText = holder.findView(R.id.text_edit);
                holder.setText(R.id.text_title, commodity.getGoodsName());
                holder.setText(R.id.text_price, "¥" + commodity.getPrice());
                Glide.with(getActivity()).
                        load(commodity.getMainPicture())
                        .error(R.mipmap.img_default).centerCrop().into(imageView);
                if (commodity.getStatus() == STATUS_OFF) {
                    offText.setText("上架");
                } else {
                    offText.setText("下架");
                }
                offText.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startRequest(commodity, position);
                    }
                });
                editText.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(getActivity(), AddCommodityActivity.class);
                        intent.putExtra(AddCommodityActivity.KEY_COMMODITY, commodity);
                        intent.putExtra(AddCommodityActivity.KEY_TYPE, AddCommodityActivity.TYPE_EDIT);
                        startActivity(intent);
                    }
                });
            }
        };
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addItemDecoration(new CustomItemDecoration(DisplayUtil.dip2px(getActivity(), 1),
                LinearLayoutManager.HORIZONTAL));
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new CustomAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
//                Intent intent = new Intent(getActivity(), CommodityDetailActivity.class);
//                intent.putExtra(AddCommodityActivity.KEY_DATA, mCommodityList.get(position));
//                startActivity(intent);
                CommodityDetailActivity.start(getActivity(), mCommodityList.get(position), 0);
            }
        });
        id = getArguments().getString(KEY_CATEGORY_ID);
        emptyViewStub.inflate();
        lazyLoad();
    }

    private void displayLoadingView(boolean display) {
        for (int i = 0; i < mContentViewLayout.getChildCount(); i++) {
            View childView = mContentViewLayout.getChildAt(i);
            if (R.id.fl_progress_bar == childView.getId()) {
                childView.setVisibility(display ? View.VISIBLE : View.GONE);
            } else {
                childView.setVisibility(display ? View.GONE : View.VISIBLE);
            }
        }
    }

    public void loadData(String id) {
        if (TextUtils.isEmpty(id)) {
            return;
        }
        int pageSize = 20;
        mCall = ApiManager.get().getApiService(ApiService.class).getCommodityList(null,
                id,
                pageIndex,
                pageSize);
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback<CommodityData>() {

            @Override
            public void onSuccess(String url, CommodityData data) {
                displayLoadingView(false);
                dismissDialog();
                if(data == null) {
                    return;
                }
                pageIndex++;
                isLoading = false;
                mPullView.onFinishFreshAndLoad();
                if (isRefresh) {
                    mCommodityList.clear();
                    if (data.getData() == null || data.getData().size() == 0) {
                        emptyViewStub.setVisibility(View.VISIBLE);
                        return;
                    } else {
                        emptyViewStub.setVisibility(View.GONE);
                    }
                } else {
                    if (data.getData() == null || data.getData().size() == 0) {
                        emptyViewStub.setVisibility(View.GONE);
                        isMore = false;
                        return;
                    }
                }
                mCommodityList.addAll(data.getData());
                mAdapter.updateView(mCommodityList);
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                isLoading = false;
                dismissDialog();
                mPullView.onFinishFreshAndLoad();
                ToastUtil.getInstance().showToast(getActivity(), "获取数据失败");
            }
        });
    }

    void lazyLoad() {
        displayLoadingView(true);
        loadData(id);
    }

    /**
     * 向服务器发起请求
     */
    public void startRequest(Commodity commodity, final int index) {
        final int status;
        showLoadingDialog();
        if (commodity.getStatus() == STATUS_OFF) {
            status = STATUS_ON;
        } else {
            status = STATUS_OFF;
        }
        call = ApiManager.get().getApiService(ApiService.class).offCommodity(commodity.getDmId(),
                id,
                status + "",
                commodity.getFinalPrice(),
                commodity.getPrice() + "",
                commodity.getMainPicture(),
                commodity.getPicture(),
                commodity.getSales() + "",
                commodity.getGoodsDesc(),
                commodity.getGoodsName(),
                commodity.getOneCategoryName(),
                commodity.getBrandId(),
                commodity.getTwoCategoryId(),
                commodity.getBusinessId(),
                commodity.getCreateTime(),
                commodity.getCreateUserId(),
                commodity.getIsRecommend() + "",
                commodity.getSort() + "",
                commodity.getShelvesTime());
        HttpRequest.getRequest().autoRecycle(this).start(call, new ResponseCallback() {
            @Override
            public void onSuccess(String url, Object data) {
                dismissDialog();
                mCommodityList.get(index).setStatus(status);
                mAdapter.updateView(mCommodityList);
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe
    public void onEvent(String data) {
        pageIndex = 1;
        lazyLoad();
    }

}
